import org.junit.Test;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

/**
 * @author 35326
 * 2021/3/24 14:13
 *
 * 1. 要用通道
 * 	|--java.nio.channels.Channel接口：
 * 		|--SelectableChannel
 * 			|--SocketChannel
 * 			|--ServerSocketChannel
 * 			|--DatagramChannel
 *
 * 			|--Pipe.SinkChannel
 * 			|--Pipe.sourceChannel
 * 2. 要有缓冲区
 * 3. 要有选择器是SelectableChannel的多路复用器。用于监控SelectableChannel的IO状况
 * 4.
 */
public class TestBlockingNIO {
	//客户端
	@Test
	public void client() throws IOException {
		//获取通道
		SocketChannel open = SocketChannel.open(new InetSocketAddress("127.0.0.2", 9999));
		//分配指定大小的缓冲区
		ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
		//从本地读取数据
		FileChannel fileChannel = FileChannel.open(Paths.get("1.jpg"), StandardOpenOption.READ);
		while(fileChannel.read(byteBuffer)!=-1){
			byteBuffer.flip();
			open.write(byteBuffer);
			byteBuffer.clear();
		}

		//关闭通道
		fileChannel.close();
		open.close();
	}

	//服务端
	@Test
	public void server() throws IOException {
		ServerSocketChannel serverSocketChannel =
				ServerSocketChannel.open();

		//绑定连接
		serverSocketChannel.bind(new InetSocketAddress(9999));

		//获取客户端连接的通道
		SocketChannel accept = serverSocketChannel.accept();

		//接收客户端的数据并保存到本地
		FileChannel fileChannel =
				FileChannel.open(Paths.get("2.jpg")
				,StandardOpenOption.WRITE,StandardOpenOption.CREATE);

		ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
		while(accept.read(byteBuffer)!=-1){
			byteBuffer.flip();
			fileChannel.write(byteBuffer);
			byteBuffer.clear();
		}

		//关闭通道
		accept.close();
		fileChannel.close();
		serverSocketChannel.close();
	}
}
